<template>
  <el-form 
    ref="formRef" 
    :model="form" 
    :rules="rules" 
    label-width="80px" 
    class="demo-ruleForm"
  >

    <el-form-item v-if="step === 1" label="电子邮箱" prop="email">
      <el-input v-model="form.email"></el-input>
    </el-form-item>
    <el-form-item v-if="step === 2" label="用户名" prop="username">
      <el-input v-model="form.userName"></el-input>
    </el-form-item>
    <el-form-item v-if="step === 2" label="验证码" prop="code">
      <el-input v-model="form.code"></el-input>
    </el-form-item>
    <el-form-item v-if="step === 2" label="新密码" prop="newPassword">
      <el-input type="password" v-model="form.newPassword"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button v-if="step === 1" type="primary" :loading="loading" @click="handleSubmitEmail">提交</el-button>
      <el-button v-else type="primary" :loading="loading" @click="handleSubmitCode">验证并重置</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
    <el-form-item>
      <el-link type="primary" @click="toggleMode('login')">返回登录</el-link>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { defineEmits } from 'vue';

// 假设这里是从环境中获取API路径
// import { API_BASE_URL } from '@/config/env';
import { sendVerificationCodeApi, resetPasswordApi } from '@/api/sys/user';

const emit = defineEmits(['toggle-mode']);

const formRef = ref(null);
const step = ref(1); // 1: 输入用户名和邮箱, 2: 输入验证码

const loading = ref(false);

const form = reactive({
  userName: '',
  email: '',
  code: '',
  newPassword: ''
});

const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

const handleSubmitEmail = async () => {
  if (!formRef.value) return;
  try {
    loading.value = true;
    await formRef.value.validateField(['username', 'email']);
    
    // 调用API发送验证码
    const data = await sendVerificationCodeApi({
      'email': form.email
    });
    if (data) {
      ElMessage({
        message:data || '验证码已发送至您的邮箱，请查收。',
        type: 'success'
      });
      step.value = 2; // 进入第二步
    } 
  } catch (error) {
    ElMessage.error('发送验证码时出现错误，请检查网络连接或稍后再试。');
  } finally {
    loading.value = false;
  }
};

const handleSubmitCode = async () => {
  if (!formRef.value) return;
  try {
    loading.value = true;
    await formRef.value.validate();
    // 调用API验证验证码并重置密码
    const data = await resetPasswordApi({ ...form });
    if (data) {
      ElNotification({
        title: '成功',
        message: '密码已成功重置。',
        type: 'success'
      });
      resetForm();
      emit('toggle-mode', 'login'); // 返回登录页面
    } else {
      ElMessage.error(response.data.message || '验证码验证失败或密码重置失败，请检查输入。');
    }
  } catch (error) {
    ElMessage.error(error);
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  step.value = 1; // 回到第一步
};

const toggleMode = (mode) => {
  emit('toggle-mode', mode);
};
</script>